package com.dlee.mvc.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.dlee.mvc.annotion.Resource;
import com.dlee.mvc.annotion.ResponseBody;
import com.dlee.mvc.container.BeanContainer;
import com.dlee.mvc.model.UrlMapping;
import com.dlee.mvc.util.StringUtils;

/** 请求转发，所有请求先进入该servlet
 * @author lida
 * @since JDK1.7
 * @history 2012-7-14 lida
 **/
public class DispatcherServlet extends HttpServlet {

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String strUrl = getRequestUrl(req);
		transferProcess(strUrl, req, resp);
	}

	/**
	 * 
	 * 备注:取处理过的请求路径 
	 * 
	 * @param req
	 * @return
	 */
	private String getRequestUrl(HttpServletRequest req) {
		// 取请求url
		String strRequestUrl = req.getRequestURI();
		String strMatchUrl = "";
		// 取?前面的字符串匹配
		int index = strRequestUrl.indexOf("?");
		if (index != -1) {
			strMatchUrl = strRequestUrl.substring(0, index);
		} else {
			strMatchUrl = strRequestUrl;
		}
		// 取servlet中配置的拦截后缀
		// int iLastDot = strMatchUrl.lastIndexOf (".");
		// strMatchUrl = strMatchUrl.substring (0, iLastDot);
		return strMatchUrl;
	}

	/**
	 * 请求转发 备注: 添加人 lida 添加时间 2013-3-15 下午05:25:52
	 * 
	 * @param req
	 */
	private void transferProcess(String matchUrl, HttpServletRequest req, HttpServletResponse resp) {
		// String contextPath = req.getContextPath ();
		// 到缓存中匹配url
		UrlMapping objUrlMapping = BeanContainer.getMapUrlMapping(matchUrl);
		try {
			if (objUrlMapping != null) {
				Class[] objClassParameter = objUrlMapping.getParameterArray();
				int iLen = objClassParameter.length;
				// 存参数
				Object[] objParameter = new Object[iLen];
				for (int i = 0; i < iLen; i++) {
					if (objClassParameter[i].getName().equals("javax.servlet.http.HttpServletRequest")) {
						objParameter[i] = req;
					}
					if (objClassParameter[i].getName().equals("javax.servlet.http.HttpServletResponse")) {
						objParameter[i] = resp;
					}
				}
				Class objClass = Class.forName(objUrlMapping.getClassPath());
				String id = StringUtils.lowerCaseFirstChar(objClass.getSimpleName());
				Object obj = BeanContainer.getBean(id);
				// Object obj = objClass.newInstance();
				Method objMethod = objClass.getMethod(objUrlMapping.getMethodName(), objClassParameter);
				ResponseBody rb = objMethod.getAnnotation(ResponseBody.class);
				Object result = objMethod.invoke(obj, objParameter);
				if (null != rb) {
					resp.getOutputStream().print(JSONObject.fromObject(result).toString());
				} else {
					if (result instanceof String) {
						// resp.getOutputStream ().print (String.valueOf
						// (result));
						req.getRequestDispatcher("/" + result.toString()).forward(req, resp);
					} else {
						System.out.println("not found view");
					}
				}
			} else {
				// 出错,转向错误页面。
				System.out.println("没有对应的请求");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
